/*
 * Copyright (C) 2009 Rafael Fernandes, Jeff Sharkey, http://jsharkey.org/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.phonebooksharing.android.widgets.desktop;

import java.util.ArrayList;

import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;

import com.phonebooksharing.android.R;
import com.phonebooksharing.android.activities.main.MainContainerActivity;
import com.phonebooksharing.android.provider.PhonebookSharing.Dashboard;
import com.phonebooksharing.android.provider.PhonebookSharing.DesktopMessage;
import com.phonebooksharing.android.provider.PhonebookSharing.DesktopWidgets;
import com.phonebooksharing.android.services.DesktopMessageUpdaterService;
import com.phonebooksharing.android.util.CloseableUtil;

/**
 * Definition of a medium-sized forecast widget. Passes any requested updates to
 * {@link DesktopMessageUpdaterService} to perform on background thread and prevent ANR.
 *
 * @author Jeff Sharkey, http://jsharkey.org/ (Examples)
 * @author Rafael Fernandes (Adapted based upon Sharkey's examples)
 */
public class TextMessageAppWidgetProvider extends AppWidgetProvider {
    private static final String TAG = "TextMessageAppWidgetProvider";

    /**
     * {@inheritDoc}
     */
    @Override
    public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
        // If no specific widgets requested, collect list of all
        if (appWidgetIds == null) {
            appWidgetIds = appWidgetManager.getAppWidgetIds(
                    new ComponentName(context, TextMessageAppWidgetProvider.class));
        }

        // Request update for these widgets and launch updater service
        DesktopMessageUpdaterService.requestUpdate(appWidgetIds);
        context.startService(new Intent(context, DesktopMessageUpdaterService.class));
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public void onDeleted(Context context, int[] appWidgetIds) {
        ContentResolver cr = context.getContentResolver();
        for (int appWidgetId : appWidgetIds) {
            Log.d(TAG, "Deleting appWidgetId = " + appWidgetId);
            Uri appWidgetUri = ContentUris.withAppendedId(DesktopWidgets.CONTENT_URI, appWidgetId);
            cr.delete(appWidgetUri, null, null);
        }
    }

    /**
     * Build an update for the given medium widget. Should only be called from a
     * service or thread to prevent ANR during database queries.
     */
    public static RemoteViews buildUpdate(Context context, Uri appWidgetUri) {
        Log.d(TAG, "Building TextMessageAppWidgetProvider update");

        RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.msg_desktop_layout);

        ContentResolver cr = context.getContentResolver();
        Cursor cursor = null, dashCursor = null;
        try {
            
            dashCursor = cr.query(Dashboard.CONTENT_URI, new String[] {Dashboard.QTY_MESSAGES}, null,null,null);
            if(!dashCursor.moveToFirst()) {
                return views;
            }
            
            views.setViewVisibility(R.id.dashboard, View.VISIBLE);
            views.setViewVisibility(R.id.qty, View.VISIBLE);
            views.setTextViewText(R.id.qty, dashCursor.getString(0));
            views.setViewVisibility(R.id.divider, View.VISIBLE);
            
            cursor = cr.query(DesktopMessage.CONTENT_URI, DesktopMessage.PROJECTION_APPWIDGETS, 
                                    DesktopMessage.TYPE + "=" + DesktopMessage.MSG_TYPE_TEXT, 
                                    null, 
                                    null);
            
            ArrayList<DesktopMessage> list = DesktopMessage.fromCursor(cursor);
            int size = list.size();
            if(size > 0) {
                views.setViewVisibility(android.R.id.empty, View.GONE);
                
                DesktopMessage dm = list.get(0);
                setRemoteValue(dm, views, R.id.contact1, R.id.when1, R.id.title1);
                if(size > 1) {
                    dm = list.get(1);
                    setRemoteValue(dm, views, R.id.contact2, R.id.when2, R.id.title2);
                }
                if(size > 2) {
                    dm = list.get(2);
                    setRemoteValue(dm, views, R.id.contact3, R.id.when3, R.id.title3);
                }
            } else {
                views.setViewVisibility(android.R.id.empty, View.VISIBLE);
            }
        } finally {
            CloseableUtil.safeClose(cursor);
            CloseableUtil.safeClose(dashCursor);
            cursor = null;
            dashCursor = null;
        }

        // Connect click intent to launch details
        Intent detailIntent = new Intent(context, MainContainerActivity.class);
        
        PendingIntent pending = PendingIntent.getActivity(context, 0, detailIntent, 0);
        views.setOnClickPendingIntent(R.id.appwidget, pending);

        return views;
    }

    protected static void setRemoteValue(DesktopMessage dm, RemoteViews views, 
                                  int contactView, int whenView, int titleView) {
        views.setViewVisibility(contactView, View.VISIBLE);
        views.setTextViewText(contactView, dm.contactName);
        views.setViewVisibility(whenView,    View.VISIBLE);
        views.setTextViewText(whenView, dm.whenFormatted);
        views.setViewVisibility(titleView,   View.VISIBLE);
        views.setTextViewText(titleView, dm.title);
    }
}
